package com.duck.inspection.controller;

import com.coze.openapi.client.files.model.FileInfo;
import com.duck.inspection.config.CozeChatApiClient;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collections;

@RestController
@RequestMapping("/coze/images")
@RequiredArgsConstructor
public class UploadCozeController {

    private final CozeChatApiClient chatApiClient;

    /**
     * 上传图片文件，返回 Coze 上的 imageId
     */
    @PostMapping("/upload")
    public ResponseEntity<?> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            // 临时存储
            String tmpPath = System.getProperty("java.io.tmpdir") + "/" + file.getOriginalFilename();
            file.transferTo(new java.io.File(tmpPath));

            // 上传给 Coze，拿到 imageId
            FileInfo info = chatApiClient.uploadFile(tmpPath);

            // 删除临时文件
            new java.io.File(tmpPath).delete();

            return ResponseEntity.ok(Collections.singletonMap("imageId", info.getID()));
        } catch (Exception e) {
            return ResponseEntity
                    .status(500)
                    .body(Collections.singletonMap("error", e.getMessage()));
        }
    }
}
